<?php
/**
 * 用户组操作
 */
class GroupHelper
{
	/**
	 * 增加一个用户组
	 */
	public static function add($title)
	{
		try {
			Db::get('Group')->insert(array('title'=>trim($title),'atime'=>time()))->exec();
		}
		catch(Exception $_){
			return false;
		}
		$group_id	=	Db::get('Group')->insertId();

		//增加虚拟组role
		RoleHelper::addGroupVirtualRole($group_id, $title);

		return $group_id;
	}

	/**
	 * 修改组信息
	 */
	public static function modify($group_id, $title)
	{
		$title	=	trim($title);
		if(!$title) {
			return false;
		}
		
		try {
			Db::get('Group')->update(array('title'=>$title))->where(array('group_id'=>$group_id))->exec();
		}
		catch(Exception $_){
			return false;
		}

		//修改虚拟组role
		if(Db::get('Group')->affectedRows() >0)
		{
			RoleHelper::modifyGroupVirtualRole($group_id, $title);
		}

		return true;
	}

	/**
	 * 删除一个组。同时删除组角色及授权。
	 */
	public static function delete($group_id)
	{
		$role_id	=	Group::instance()->getVirtualRoleId($group_id);
		if(!$role_id) {
			return false;	//无此group_id
		}
		//删除角色及角色授权
		if(RoleHelper::delete($role_id))
		{
			if(Db::get('Group')->delete()->where(array('group_id'=>$group_id))->exec())
			{
				return Db::get('User')->update(array('group_id'=>0))->where(array('group_id'=>$group_id))->exec();
			}
		}
		else {
			return false;
		}
	}

}
?>